package com.seqb.manage.picture.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.RandomUtil;
import com.seqb.common.Query;
import com.seqb.common.config.SeqbConfig;
import com.seqb.manage.picture.service.PictureService;
import com.seqb.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2021/6/23
 */
@Service
public class PictureServiceImpl implements PictureService {

    @Autowired
    private SeqbConfig seqbConfig;

    @Override
    public PageUtils list(Query query) {
        int pageSize = 12;
        int pageNumber = 1;
        if (query != null && query.size() > 0) {
            pageNumber = query.getPageNumber();
            pageSize = query.getPageSize();
        }
        List fileLists = new ArrayList();
        //列出目录文件
        File[] ls = FileUtil.ls(seqbConfig.getUploadPath() + "/picture");
        for (File item : ls) {
            Map<String, Object> itemMap = new HashMap<>();
            itemMap.put("name", item.getName());
            List fileChildList = new ArrayList();
            List<File> fileList = FileUtil.loopFiles(item);
            Collections.sort(fileList, new Comparator<File>() {
                @Override
                public int compare(File o1, File o2) {
                    String o1Name = FileNameUtil.getPrefix(o1);
                    String o2Name = FileNameUtil.getPrefix(o2);
                    return Integer.valueOf(o1Name).compareTo(Integer.valueOf(o2Name));
                }
            });
            for (int i = 0; i < fileList.size(); i++) {
                Map<String, Object> itemChildMap = new HashMap<>();
                File child = fileList.get(i);
                if (i == 0) {
                    itemMap.put("url", "/files/picture/" + item.getName() + "/" + child.getName());
                }
                itemChildMap.put("name", child.getName());
                itemChildMap.put("url", "/files/picture/" + item.getName() + "/" + child.getName());
                fileChildList.add(itemChildMap);

            }
            itemMap.put("id", RandomUtil.randomNumbers(6));
            itemMap.put("list", fileChildList);
            fileLists.add(itemMap);
        }

        int total = fileLists.size();
        if (total > (pageSize * pageNumber)) {
            fileLists = fileLists.subList(pageSize * (pageNumber - 1), pageSize * pageNumber);
        } else if (pageSize * (pageNumber - 1) < total && total < (pageSize * pageNumber)) {
            fileLists = fileLists.subList(pageSize * (pageNumber - 1), total);
        }
        return new PageUtils(fileLists, total);
    }

}
